
/*
 * @Author: ZephyrGao
 * @Date: 2024-02-28 08:12:06
 * @Description: 
 * Copyright (c) 2024 by ZephyrGao, All Rights Reserved. 
 */

import AxiosHelper from '@/helper/axiosHelper';
import { defineStore } from "pinia";

export const useUserStore = defineStore('user', {

  state: () => ({
    token: '',
    userInfo: {},
  }), 
  persist: [
    {
      paths: ['token'],
      storage: localStorage,
    },
    // {
    //   paths: ['toSession'],
    //   storage: sessionStorage,
    // },
  ],
  actions: {
    // 登录
    async login(data: { username: string; password: string }) {
      // const response = await AxiosUtil.post('/api/login', data);

      // const { username, password } = data;
      try {
        const response = AxiosHelper.post('/api/login', data);
        console.log('login successful:', response);
        return { success: true, message: 'Registration successful' };
      } catch (error) {
        // Handle registration failure, e.g., show error message
        console.error('error failed:', error);
        return { success: false, message: 'Registration failed' };
      }
    },
    // 注册
    async register(data: { username: string; password: string }) {
      // const { username, password } = data;
      try {
        // Clear the token from the store
        // this.clearToken();

        // Redirect to the login page or perform any other necessary logout actions
        // Replace the example navigation with your actual navigation logic
        // For example, you might use a router library like Vue Router
        // router.push({ name: 'login' });

        // Return any additional information needed by the component
        return { success: true, message: 'Logout successful' };
      } catch (error) {
        // Handle logout failure, e.g., show error message
        console.error('Logout failed:', error);
        return { success: false, message: 'Logout failed' };
      }
    },
    // 三方登录


    // 退出登录
    async logout() {
      // 退出登录
      // 1. 删除token
      // 2. 退出所有页面并返回登录页
      // 3. 清除vuex中的token
    }
  },
  getters: {
    // 是否已登录
    getIsLogin: (state: any) => {
      return state.token !== '';
    },
    getToken: (state) => state.token,
    isAuthenticated: (state) => state.token !== null,
  }
})